<!-- 实时数据 -->
<template>
  <div class="lc_wrap">
    <el-row class="RealdataTabel loamRealdataTabel">
      
      <!-- 左侧树 -->
      <el-col :span="leftWidth" v-show="false">
        <div class="box treeBox">
          <basic-container>
            <lcCheckBoxTree @ready="ready" :deviceType="3"></lcCheckBoxTree>
          </basic-container>
        </div>
      </el-col>

      <!-- 内容 -->
      <el-col :span="24" class="table-wrapper merge_table_wrapper">
        <!-- <overlay @changeTreeBox="changeTreeBox"></overlay> -->
        <basic-container class="loam_real_container">

          <!-- 表格内容 -->
          <avue-crud
            ref="crud"
            v-model="form"
            :option="option"
            :table-loading="loading"
            :data="data.filter((item) => item.deptName.includes(loamCompanyName))"
            :cell-style="cellStyle"
            v-if="showTabel"
            :span-method="objectSpanMethod"
          >

            <!-- 左上方菜单 -->
            <template slot="menuLeft">

					    <el-row :gutter="20">     
					      <el-col :span="6">
					        <div class="grid-content filter-content">
					          <el-input
					            placeholder="请输入 企业名称"
					            prefix-icon="el-icon-search"
					            
					            v-model="loamCompanyName">
					          </el-input>
					        </div>
					      </el-col>      
					      <el-col :span="12" >
					        <div class="grid-content">
					          <el-row :gutter="2">
					            <el-col :span="3"><div class="grid-content" :class="{active:active==0}" @click="filterData(0)">全部({{ totalCom }})</div></el-col>
					            <el-col :span="3"><div class="grid-content" :class="{active:active==1}" @click="filterData(1)">正常({{ normalCom }})</div></el-col>
					            <el-col :span="3"><div class="grid-content" :class="{active:active==2}" @click="filterData(2)">异常({{ abnormalCom }})</div></el-col>
					            <el-col :span="3"><div class="grid-content" :class="{active:active==3}" @click="filterData(3)">在线({{ onlineCom }})</div></el-col>
					            <el-col :span="3"><div class="grid-content" :class="{active:active==4}" @click="filterData(4)">离线({{ offlineCom }})</div></el-col>
					          </el-row>
					        </div>
					      </el-col>
					
					    </el-row>              
              
              
              
            </template>

            <!-- 右上方菜单 -->
            <template slot="menuRight">
              <el-button
                type="warning"
                size="small"
                plain
                icon="el-icon-download"
                @click="handleExport">
                导 出
              </el-button>
              <el-button
                class="refresh-count"
                style="margin:0px 0px 15px 5px;" 
                size="small"
                type="primary"
                v-if="showTabel"
                icon="el-icon-refresh"
                @click="countNum = 0">
                刷新倒计时 {{ countNum }}s
              </el-button>
            </template>

            <template
              :slot="item.alias"
              slot-scope="scope"
              v-for="(item, index) in factorList"
            >
              <div
                :key="index"
                v-if="scope.row[item.alias + 'isAbnormal'] === 1 && item.alias !== '风机' && item.alias !== '净化器'"
                style="color: red;"
              >
                {{ scope.row[item.alias] }}
              </div>
              <div :key="index" v-else v-html="scope.row[item.alias]"></div>
            </template>
          </avue-crud>
        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getListHead, getListData, getDeptTree } from "@/api/loam/realdata";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import lcCheckBoxTree from "@/components/common/tree_checkBox.vue";
import overlay from "@/components/common/overlay.vue";
import { mergeTableRow } from "@/util/merge";
export default {
  components: {
    lcCheckBoxTree, overlay
  },
  data() {
    return {
      loamCompanyName: "",
      alltableData:null,
      comSpan: "deptName-span",
      showTabel: true,
      leftWidth: this.$leftWidth,
      rightWidth: this.$rightWidth,
      totalCom: 0,
      normalCom: 0,
      abnormalCom: 0,
      onlineCom: 0,
      offlineCom: 0,
      active:0,      
      form: {},
      loading: false,
      option: {
        menu: false,
        menuTitle: "视频播放",
        editBtn: false,
        delBtn: false,
        addBtn: false,
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        dialogClickModal: false,
        refreshBtn: false,
        index: false,
        selection: false,
        columnBtn: false,
        column: []
      },
      data: [],
      timer: null,
      countNum: "-", // 刷新的倒计时·
      nodeList: [], // 存放已勾选节点value的数组（底层节点)
      factorList: [],
      t2: null,
      MOTION_STATE: '运行状态'
    };
  },
  props: {
    systemId: {
      type: Number,
      default: 0
    }
  },
  computed: {
    ...mapGetters(["permission"])
  },
  watch: {

    // 倒计时结束时刷新表格
    countNum(val) {
      if (val == 0) {
        clearInterval(this.timer);
        this.timer = null;
        this.loading = true;
        this.getRealData();
      }
    }
  },
  methods: {
  	filterData(active){
  		this.loamCompanyName=''
  		this.active=active
  		if(active==0){
  			this.data=this.alltableData
  		}else if(active==1){
  			this.data=this.alltableData.filter((data) => data.filterStatus==1||data.filterStatus==3)
  		}else if(active==2){  			
  			this.data=this.alltableData.filter((data) => data.filterStatus==2)
  		}else if(active==3){  			
  			this.data=this.alltableData.filter((data) => data.filterStatus==1||data.filterStatus==2)
  		}else if(active==4){  			
  			this.data=this.alltableData.filter((data) => data.filterStatus==3)
  		}  		
  	},  	
    // 左侧树加载事件
    ready(val) {
      this.nodeList = val;
      clearTimeout(this.t2);
      this.t2 = null;
      clearTimeout(this.timer);
      this.timer = null;
      this.t2 = setTimeout(() => {
        this.getRealData();
      }, 100);
    },

    // 导出
    handleExport() {
      this.$confirm("是否导出实时数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let treeIds = this.nodeList.join(",");
        window.open(
          `/api/squirrel-loam/latestData/export?${this.website.tokenHeader}=${getToken()}&treeIds=${treeIds}`
        );
      });
    },

    // 获取表头
    getRealData() {
      let treeId = this.nodeList;
      let TreeIdsVO={
      	ids:treeId
      }
      if (treeId.length <= 0) {
        this.showTabel = false;
        return false;
      } else {
        this.showTabel = true;
      }
      this.loading = true;
      getListHead(TreeIdsVO).then(res => {
          if (res.data.success) {
            // 封装表头
            let tableHead = [{
              label: "序号",
              prop: "Lindex",
              align: "center",
              hide: false,
              width: 60
            }, {
              label: "状态",
              prop: "status",
              align: "center",
              width:60
            }, {
              label: "区域名称",
              prop: "regionName",
              align: "left"
            }, {
              label: "企业名称",
              prop: "deptName",
              align: "left",
              width:200,
              align:'left'
            }, {
              label: "排口名称",
              prop: "siteName",
              align: "left",
              width:150,
            }, {
              label: "机组名称",
              prop: "groupName",
              align: "left",
              width:130
            }, {
              label: "上传时间",
              prop: "collectTime",
              align: "center",
              width: 150
            }];

            // 插入除运行状态外的因子
            res.data.data.forEach(item => {
              if (item.alias !== this.MOTION_STATE) {
                tableHead.push({
                  label: item.alias + "\n(" + item.unit + ")",
                  prop: item.alias,
                  align: this.$tabelAlgin,
                  slot: true
                });
                this.factorList.push(item);
              }
            });

            // 插入风机运行状态中的因子
            res.data.data.forEach(item => {
              if (item.alias === this.MOTION_STATE) {
                // 插入运行状态
                tableHead.push({
                  label: this.MOTION_STATE,
                  prop: "motionState",
                  align: "center",
                  children: []
                });

                item.children.forEach(childItem => {
                  tableHead.forEach(head => {
                    if (head.label === this.MOTION_STATE) {
                      head.children.push({
                        label: `${childItem.alias}`,
                        prop: childItem.alias,
                        align: "center",
                        slot: true,
                        width: 70
                      });
                      this.factorList.push(childItem);
                    }
                  });
                });
              }
            });

            // 将表头放入option
            this.option.column = tableHead;
          }
        })
        .then(() => {
          this.getTableData();
        });
    },

    // 左侧树收缩、展开
    changeTreeBox() {
      this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
      this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
    },

    // 单元格样式
    cellStyle({ row }) {
      return row.isAbnormal ? {color: "red"} : {};
    },

    // 获取实时数据
    getTableData() {
      let _this = this;
      let treeId = this.nodeList;
      let TreeIdsVO={
      	ids:treeId
      }
      getListData(TreeIdsVO).then(res => {
        if (res.data.success) {
          _this.data = [];          
	        this.totalCom = res.data.data.deptStatusCount.total? res.data.data.deptStatusCount.total: 0;
	        this.abnormalCom = res.data.data.deptStatusCount.abnormal? res.data.data.deptStatusCount.abnormal: 0;
	        this.offlineCom = res.data.data.deptStatusCount.offLine? res.data.data.deptStatusCount.offLine: 0;
	        this.normalCom = this.totalCom - this.abnormalCom;
	        this.onlineCom = this.totalCom - this.offlineCom;          
          // 遍历表格体接口返回数据
          var gisVOList = [];
          res.data.data.gisVOList.forEach(item => {
            var obj = {
              status: item.status,
              regionName: item.regionName || "-",
              deptName: item.deptName || "-",
              siteName: item.siteName || "-",
              groupName: item.groupName || "-",
              collectTime: item.collectTime || "-",
              deptInfoId:item.deptInfoId
            };

            // 根据动态表头创建因子字段 并默认初始值
            _this.factorList.forEach(el => {
              obj[el.alias] = "-";
              obj[el.alias + 'isAbnormal'] = 0
            });

            // 接口因子值
            item.factorList.forEach(el => {
              for(var x in obj) {
                if(el.alias + 'isAbnormal' == x) {
                  obj[el.alias + 'isAbnormal'] = el.isAbnormal;
                }
              }
              obj[el.alias] = el.collectValue || "-";
            });

            // 表格数据赋值
            gisVOList.push(obj);
          });
          
          // 该企业下所有排口、机组的状态
          var statusListObj = {};
          gisVOList.forEach((item) => {
            if (statusListObj[item.deptName + "-" + item.regionName] === undefined) {
              statusListObj[item.deptName + "-" + item.regionName] = [item.status];
            } else {
              if (statusListObj[item.deptName + "-" + item.regionName].indexOf(item.status) < 0) {
                statusListObj[item.deptName + "-" + item.regionName].push(item.status);
              }
            }
            
          });
          
          // 只要有一个超标，就算超标， 全部离线才算离线
          var statusList = [];
          for (var deptRegion in statusListObj) {
            var this_status = "";
            if (statusListObj[deptRegion].length === 1) {
              this_status = statusListObj[deptRegion][0];
            } else {
              if (statusListObj[deptRegion].indexOf("2") >= 0) this_status = "2";
              else this_status = "1";
            }
            statusList.push({
              deptName: deptRegion.split("-")[0],
              regionName: deptRegion.split("-")[1],
              status: this.formatStatusHtml(this_status),
              filterStatus:this_status              
            });
          }
          
          // 企业状态图标
          gisVOList.forEach((item) => {
            for (var i = 0; i < statusList.length; i++) {
            	// 处理序号问题
              if (statusList[i].deptName === item.deptName &&statusList[i].regionName === item.regionName) {
                item.status = statusList[i].status;
                item.Lindex = i + 1;
                item.filterStatus=statusList[i].filterStatus
              }
            }
            item["风机"] = this.formatMotionHtml(item["风机"]);
            item["净化器"] = this.formatMotionHtml(item["净化器"]);
          });                    
          gisVOList=gisVOList.sort(_this.loamSort)
          _this.alltableData = mergeTableRow(
            gisVOList,
            ["Lindex", "status", "regionName", "deptName", "siteName"]
          );
         
          _this.filterData(_this.active)
          _this.countNum = 60;
          _this.timer = setInterval(() => {
            _this.countNum--;
          }, 1000);
          _this.loading = false;
        } else {
          _this.loading = false;
        }
      });
    },

    // 动态合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const span = column["property"] + "-span";
      var columns = ["Lindex-span", "regionName-span", "status-span"];
      if (row[span]) {
        if (columns.indexOf(span) >= 0) {
          return row[this.comSpan];
        }
        if (span === "siteName-span") {
          if (row[span].colspan === 1 && row[this.comSpan].colspan === 1 && row[span].rowspan > row[this.comSpan].rowspan) {
            return row[this.comSpan];
          }
          if (row[span].colspan === 0 && row[span].rowspan === 0 && (row[this.comSpan].colspan !== 0 || row[this.comSpan].rowspan !== 0) ) {
            return row[this.comSpan];
          }
        }
        return row[span];
      }
    },

    // 按照企业、排口排序
    loamSort(ob1, ob2) {
      if (ob1.Lindex < ob2.Lindex) {
        return -1;
      } else if (ob1.Lindex > ob2.Lindex) {
        return 1;
      }
      if (ob1.deptInfoId < ob2.deptInfoId) {
        return -1;
      } else if (ob1.deptInfoId > ob2.deptInfoId) {
        return 1;
      }
      if (ob1.regionName < ob2.regionName) {
        return -1;
      } else if (ob1.regionName > ob2.regionName) {
        return 1;
      } else {
        return 0;
      }
    },

    // 状态图标
    formatStatusHtml(status) {
      var imgSrc = "";
      if (status === "1") imgSrc = "/img/bg/normal.png";
      else if (status === "2") imgSrc = "/img/bg/abnormal.png";
      else if (status === "3") imgSrc = "/img/bg/offline.png";
      return (
        '<image style="width:25px;height:25px;" src="' + imgSrc + '"></image>'
      );
    },

    // 运行状态（风机、净化器）图标
    formatMotionHtml(value) {
      var imgSrc = "";
      if (value === "1") imgSrc = "/img/bg/normal.png";
      else if (value === "0") imgSrc = "/img/bg/offline.png";
      if (imgSrc !== "")
        return (
          '<image style="width:25px;height:25px;" src="' + imgSrc + '"></image>'
        );
      else return "-";
    }
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
  }
};
</script>

<style lang="scss">
.RealdataTabel {
  .el-table__empty-block {
    width: 100% !important;
  }
  .avue-crud__pagination {
    display: none;
  }
  .table-wrapper {
    .el-card {
      overflow: scroll;
      .el-card__body {
        height: calc(100% - 35px);
        .avue-crud {
          height: calc(100% - 65px);
        }
      }
    }
    .el-table__fixed {
      height: calc(100% - 12px) !important;
    }
    .el-table__fixed-right {
      height: calc(100% - 12px) !important;
    }
    .el-table__fixed-right::before,
    .el-table__fixed::before {
      height: 0px;
    }
  }
  .el-tree {
    width: 100%;
    overflow: scroll;
  }
}

.loamRealdataTabel {
  .el-table th>.cell {
    white-space: pre-line;
  }
  .avue-crud__menu{align-items: center;}
  .avue-crud__left{
  	flex: 1;
  }
}
</style>
<style lang="scss" scoped>
	.el-row {
	  height: calc(100% - 20px);
	}
	
	.el-col {
	  height: 100%;
	}
	
	.box {
	  height: 100%;
	  margin-bottom: 0;
	  margin-right: $common_margin_right;
	}
  .grid-content {
  	cursor: pointer;
    height: 50px;
    line-height: 50px;
  }
  .grid-content.active{font-weight: bold;font-size: 16px!important;}


</style>
